home *** CD-ROM | disk | FTP | other *** search
- Path: news.th-darmstadt.de!news
- From: Enno Sandner <enno@intellektik.informatik.th-darmstadt.de>
- Newsgroups: comp.lang.c++
- Subject: Re: Help: How to initialize objects created by new class[x]
- Date: Fri, 05 Jan 1996 11:15:35 +0100
- Organization: Fachbereich Informatik, TH Darmstadt
- Message-ID: <30ECFA47.446B9B3D@intellektik.informatik.th-darmstadt.de>
- References: <4cicd6$lsv@news.capitalnet.com>
- NNTP-Posting-Host: kitz.intellektik.informatik.th-darmstadt.de
- Mime-Version: 1.0
- Content-Type: text/plain; charset=us-ascii
- Content-Transfer-Encoding: 7bit
- X-Mailer: Mozilla 2.0b4 (X11; I; SunOS 4.1.3 sun4m)
-
- wingl@capitalnet.com wrote:
- >
- > Let say I have the following class
- >
- > My_class {
- > public:
- > int (int i=0) : a(i), b(i) {}
- > private:
- > int a, b;
- > }
- >
- > For the following statement, default constructor is involved upon
- > the creation of the object.
- >
- > My_class* my_ptr= new My_class;
- >
- > However, if I use
- > My_class* my_ptr= new My_class[10];
- >
- > to allocate 10 objects of class My_class, then C++ would not
- > call any constructor to do any initialization. All the objects
- > allocated are not initializated at all.
- >
- > I wonder what is the proper way to perform object initialization
- > whenever an array of objects are created? As long as a constructor
- > is involved for each of the object in the array, I don't care if all the
- > objects are initializated the same or not.
- >
- > If there is no way to get constructor to initialize an array of objects
- > upon creation. Does that means one should not do so?
- >
-
- That's not true. The expression 'new My_class[10]' should call the
- default-ctor of 'My_class' for each element.
- (I will assume the class looks like
-
- class My_class {
- public:
- My_class (int i=0) : a(i), b(i) {}
- private:
- int a, b;
- };
-
- ).
- The problems start when your class doesn't provide a default-ctor
- or you want to initialize elements of the array with different values.
- Here you are out of luck, because C++ doesn't provide an appropriate
- syntax. You'll have to use some hack like using the placement-new/delete
- operators.
-
- Enno
-